// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("\\d*")) {
textField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
String value = tf.getText();
int l = value.length();
if (ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9'|| ke.getKeyCode()==KeyEvent.VK_BACK_SPACE) {
tf.setEditable(true);
label.setText("");
} else {
tf.setEditable(false);
label.setText("* Enter only numeric digits(0-9)");
}
}
});
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);
// If you want the value to be committed on each keystroke instead of focus lost
formatter.setCommitsOnValidEdit(true);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
// getValue() always returns something valid
System.out.println(field.getValue());